<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/4
 * Time: 9:44
 */

namespace app\admin\controller;


use app\Model\DeliveryDocModel;
use app\Model\GoodsModel;
use app\Model\OrderGoodsModel;
use app\Model\OrderModel;
use app\Model\ReturnGoods;
use app\Model\SpecGoodsPriceModel;
use app\Model\UsersModel;
use app\Model\AccountLogModel;
//退货单
class Deliverylist extends Common
{
    /*
     *  退货单列表
     */
    public function index(){
        $postData = input('get.');
        $where=[];
        if (isset($postData['order_sn'])){
            if ($postData['order_sn']!=''){//订单编号
                $where['r_g.order_sn'] = ['LIKE', '%'.$postData['order_sn'].'%'];
            }
            if ($postData['status']!=-1){//状态
                $where['r_g.status'] = ['=', $postData['status']];
            }
        }
        $getDelivery= ReturnGoods::alias('r_g')->
            join('tp_goods g','r_g.goods_id=g.goods_id')->
            order('addtime','desc')->
            where($where)->//筛选
//        ->whereTime('create_time', 'between', [$time[0], $time[1]])//筛选时间
        paginate(null,false,['query'=>request()->param()]);
        $data['data'] = $getDelivery;
        $this->getConAndAct('order');

        return view('index',$data);
    }

    /*
     * 编辑退货申请页面
     */
    public function add()
    {
        $getData=input('get.');
//        dump($getData);
        $data['delivery'] =ReturnGoods::alias('r_g')//退货申请信息
            ->field('r_g.id,r_g.order_id,r_g.order_sn,r_g.goods_id,r_g.type,r_g.reason,r_g.imgs,r_g.addtime,r_g.status,r_g.remark,r_g.user_id,r_g.spec_key,r_g.rec_id')
            ->join('tp_order_goods o_g','r_g.rec_id=o_g.rec_id')
            ->field('o_g.goods_num,o_g.spec_key_name,o_g.goods_name')
            ->join('tp_users u','r_g.user_id=u.user_id')
            ->field('u.nickname')
            ->find($getData["id"]);
        //规格中文
        if ($data['delivery']['imgs']){
            $return_goods = explode(',',$data['delivery']['imgs']);
            $data['return_goods']=$return_goods;
        }
        return view('add',$data);
    }

    /*
     * 编辑退货申请
     */
    public function addData()
    {
        $postData=input('post.');
//        dump($postData);die();
        //退货申请表编辑
        $updata=[
            'id'=>$postData['id'],
            'type'=>$postData['type'],// 0 退货，1 换货
            'status'=>$postData['status'],//状态0 未处理， 1 处理中 2 处理完
            'remark'=>$postData['remark'],//备注
        ];

        $setDelivery = ReturnGoods::where('id','=',$postData['id'])->update($updata); //退货申请表编辑
//        setDatabaseDef($setDelivery,'没有修改信息');
//        商品状态修改
        $where=[
            'order_id'=>$postData['order_id'],
            'goods_id'=>$postData['goods_id'],
        ];
        $typeTOsend=[3,2];//0=>3 退货； 1=>2 换货  order_good表
        $getOG = OrderGoodsModel::where($where)->select();

//        dump($getOG->toArray());die();$typeTOsend[$postData['type']]
        $setOrderGoods =  OrderGoodsModel::where('rec_id','=',$postData['rec_id'])->update(['is_send'=>$typeTOsend[$postData['type']]]);//商品状态修改
//        setDatabaseDef($setOrderGoods,'商品状态修改失败');
//        退货需要将物品返回仓库（库存）
        if ($postData['type']==0&&$postData['status']==2){
//     未完待续
           $getGoods= ReturnGoods::find($postData['id']);
           if ($getGoods->spec_key!=''){//有规格
               //相应规格添加数量
              $setCount= SpecGoodsPriceModel::where('goods_id','=',$postData['goods_id'])->where('key','=',$getGoods->spec_key)->setInc('store_count',$postData['goods_num']);
           }else{
               $setCount = GoodsModel::where('goods_id','=',$postData['goods_id'])->setInc('store_count',$postData['goods_num']);
           }
            setDatabaseDef($setCount,'库存添加失败');
        }

//        $order=OrderModel::find($postData['order_id']);
        $type = [ '退货' ,'换货'];
        $status = [0 =>"未处理", 1=>" 处理中", 2=>" 处理完"];
        $action='退换货：'.$type[$postData['type']]."。状态：".$status[$postData['status']];
        $this->orderActionLog($postData['order_id'],$action,$postData['remark']); //订单操作记录添加
        return retJson('',200,$action);

    }
    //退款
    public function drawing()
    {
        $postData = input('post.');
        $status = ReturnGoods::where($postData)->where('status','=',2)->count();
        //判断是否已退款
        if ($status==0) {
            $where['order_id'] = $postData['order_id'];
            $where['goods_id'] = $postData['goods_id'];
            $where['rec_id'] = $postData['rec_id'];
            //
            $order_amount = OrderGoodsModel::where($where)->value('member_goods_price');
            $res = UsersModel::where('user_id','=', $postData['user_id'])->setInc('user_money', $order_amount);//用户余额添加
            $res = UsersModel::where('user_id','=', $postData['user_id'])->setDec('accu_money', $order_amount);//用户累积消费金额减少
            $status = ReturnGoods::where($postData)->update(['status'=>2]);
            //用户资金日志添加
//            dump($status);
            $this->accountlog($postData['order_id'],2,$postData['order_sn'],$order_amount,$postData['user_id']);
            if ($res) {
                return retJson('', 200, '退款成功');
            }
            return retJson('', 201, '退款失败');
        }
        return retJson('', 202, '已退款');
    }
    /**
     * @param $order_id 订单id
     * @param $desc     描述
     * @param $order_sn 订单编号
     * @param $user_money 用户金额
     * 用户资金日志添加
     */
    public function accountlog($order_id,$desc,$order_sn,$user_money,$user_id){
        switch ($desc){
            case 1:
                $desc='下单消费';
                $user_money='-'.$user_money;
                break;
            case 2:
                $desc='退货，退回'.$user_money.'元';
                $user_money='+'.$user_money;
                break;
        }
        $data =[
            'order_id'=>$order_id,
            'user_id'=>$user_id,
            'change_time'=>time(),
            'order_sn'=>$order_sn,
            'user_money'=>$user_money,
            'desc'=>$desc
        ];
        AccountLogModel::insert($data);
        return;
    }

    /*
     * 退货申请删除
     */
    public function del(){
        $getData = input('post.');
//        dump($getData);die();

        $delRole = ReturnGoods::destroy($getData['id']);
        return setDatabase($delRole);
    }

}